package com.qf.springbootshiro.shiroconfig;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        //免登录的url
        chainDefinition.addPathDefinition("/register.html", "anon");
        chainDefinition.addPathDefinition("/favicon.ico", "anon");
        chainDefinition.addPathDefinition("/user/login", "anon");
        chainDefinition.addPathDefinition("/user/register", "anon");
        chainDefinition.addPathDefinition("/error", "anon");
        chainDefinition.addPathDefinition("/login", "anon");
        chainDefinition.addPathDefinition("/test1", "anon");
        // cookie免登录可以直接访问的资源url
        chainDefinition.addPathDefinition("/home.html", "user");
        //需要登陆的url
        chainDefinition.addPathDefinition("/**", "authc");
        return chainDefinition;
    }

    @Bean
    public Realm customRealm() {
        CustomRealm customRealm = new CustomRealm();
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName("md5");
        credentialsMatcher.setHashIterations(1024);
        customRealm.setCredentialsMatcher(credentialsMatcher);
        // 整合缓存配置
        customRealm.setCacheManager(new EhCacheManager());
        // 开启缓存
        customRealm.setCachingEnabled(true);
        // 开启身份认证缓存
        customRealm.setAuthenticationCachingEnabled(true);
        // 开启授权数据缓存
        customRealm.setAuthorizationCachingEnabled(true);

        return customRealm;
    }
}
